﻿using Basic.WxApiService.ApiInterface;
using Basic.WxApiService.Interface;
using Basic.WxApiService.WxModel;
using Basic.WxExtendService.Interface;
using Basic.WxModel.WxPlatform;
using WeDonekRpc.CacheClient.Interface;
using WeDonekRpc.Client.Attr;

namespace Basic.WxApiService.WxPlaform
{
    [ClassLifetimeAttr(ClassLifetimeType.SingleInstance)]
    internal class WxPlaformTokenService : IWxPlaformTokenService
    {
        private readonly IRedisCache _Cache;
        private readonly IWxPlatformApi _PlatformApi;
        private readonly IWxPlatformCacheService _Service;
        private readonly IWxVerifyTicketService _VerifyTicket;

        public WxPlaformTokenService (IRedisCache cache,
            IWxPlatformApi platformApi,
            IWxPlatformCacheService service,
            IWxVerifyTicketService verifyTicket)
        {
            this._Cache = cache;
            this._PlatformApi = platformApi;
            this._Service = service;
            this._VerifyTicket = verifyTicket;
        }

        public string Reset (string appId)
        {
            string verifyTicket = this._VerifyTicket.GetVerifyTicket(appId);
            WxPlatformDto platform = this._Service.GetPlatform(appId);
            return this._PlatformApi.ApplyToken(platform, verifyTicket);
        }
        public IComponentToken GetToken (string appId)
        {
            string name = string.Concat("WxPlaformToken_", appId);
            if (this._Cache.TryGet(name, out string tokenId))
            {
                return new ComponentToken(tokenId, appId, this);
            }
            else
            {
                string token = this.Reset(appId);
                return new ComponentToken(token, appId, this);
            }
        }
    }
}
